'use strict';

const { getConfig } = require('uni-config-center');
const db = uniCloud.database();

const WECHAT_API_URL = 'https://api.weixin.qq.com';
const ACCESS_TOKEN_CACHE_KEY = 'wechat_access_token';
const AHEAD_OF_EXPIRY = 200;

async function getAccessToken() {
    const cacheCollection = db.collection('system_cache');
    const cacheDoc = await cacheCollection.doc(ACCESS_TOKEN_CACHE_KEY).get();

    if (cacheDoc.data.length > 0 && cacheDoc.data[0].expires > Date.now()) {
        return cacheDoc.data[0].value;
    }

    const zhentouConfig = getConfig('zhentou-config');
    // 安全检查：确保wx配置存在
    if (!zhentouConfig || !zhentouConfig.wx) {
        throw new Error('配置错误：zhentou-config.json中缺少wx配置项');
    }
    const { appid, secret } = zhentouConfig.wx;

    if (!appid || !secret || appid === 'YOUR_WECHAT_APPID') {
        throw new Error('微信AppID或Secret未配置，请在zhentou-config/config.json中配置');
    }

    const tokenUrl = `${WECHAT_API_URL}/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;

    const res = await uniCloud.httpclient.request(tokenUrl, {
        dataType: 'json'
    });

    if (res.status !== 200 || !res.data || !res.data.access_token) {
        throw new Error(`获取access_token失败: ${res.data.errmsg || '网络错误'}`);
    }

    const { access_token, expires_in } = res.data;
    const expires = Date.now() + (expires_in - AHEAD_OF_EXPIRY) * 1000;

    await cacheCollection.doc(ACCESS_TOKEN_CACHE_KEY).set({
        value: access_token,
        expires: expires
    });

    return access_token;
}

exports.main = async (event, context) => {
    const { action, params } = event;
    let result = {};

    switch (action) {
        case 'getAccessToken':
            try {
                const accessToken = await getAccessToken();
                result = { code: 0, accessToken };
            } catch (e) {
                result = { code: 500, message: e.message };
            }
            break;
        default:
            result = {
                code: 400,
                message: '未知操作'
            };
    }

    return result;
};